package xyz.labmem.base.sys.config

import cn.dev33.satoken.interceptor.SaAnnotationInterceptor
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.CacheControl
import org.springframework.http.converter.HttpMessageConverter
import org.springframework.http.converter.StringHttpMessageConverter
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Component
import org.springframework.web.servlet.config.annotation.*
import java.nio.charset.Charset
import java.util.concurrent.TimeUnit


/**
 * @Author lty
 * @Date 2021/12/14 16:01
 */
@Configuration
@Component
class WebConfig : WebMvcConfigurer {

    override fun addResourceHandlers(registry: ResourceHandlerRegistry) {
        //swaggerUI
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/")
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/")
        //静态文件
//        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/")
//            .setCacheControl(CacheControl.maxAge(12, TimeUnit.HOURS).cachePublic())
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/favicon.ico")
            .setCacheControl(CacheControl.maxAge(12, TimeUnit.HOURS).cachePublic())
    }

    override fun configureMessageConverters(converters: MutableList<HttpMessageConverter<*>>) {
        converters.add(StringHttpMessageConverter(Charset.forName("UTF-8")))
    }

    /**
     * 跨域配置
     *
     * @param registry
     */
    override fun addCorsMappings(registry: CorsRegistry) {
        registry.addMapping("/**")
            .allowedOriginPatterns("*")
            .allowedMethods("POST", "GET", "PUT", "OPTIONS")
            .allowCredentials(true)
            .maxAge(3600)
            .allowedHeaders("*")
    }

    /**
     * 加密方式注册
     */
    @Bean
    fun passwordEncoder(): PasswordEncoder = BCryptPasswordEncoder()

    /**
     * 注册 Sa-Token 路由拦截器
     */
    override fun addInterceptors(registry: InterceptorRegistry) {
        //注解权限
        registry.addInterceptor(SaAnnotationInterceptor()).addPathPatterns("/**")
    }
}